package com.hejielife.balking4;

/**
 * 2019年8月2日 下午1:41:27
 * 
 * @author hejielife
 * @despribe Host超时报警
 */
public class Host {
	private final long timeout; // timeoutֵ time
	private boolean ready = false; // 是否执行

	public Host(long timeout) {
		this.timeout = timeout;
	}

	public synchronized void setExecutable(boolean on) {
		ready = on;
		notifyAll();
	}

	public synchronized void execute() throws InterruptedException, TimeoutException {
		long start = System.currentTimeMillis();
		while (!ready) {
			long now = System.currentTimeMillis();
			long rest = timeout - (now - start);
			if (rest <= 0) {
				throw new TimeoutException("now - start = " + (now - start) + ", timeout = " + timeout);
			}
			wait(rest);
		}
		doExecute();
	}

	private void doExecute() {
		System.out.println(Thread.currentThread().getName() + " calls doExecute");
	}
}
